<template>
  <div class='container'>
    <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog" width="30%">
      <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学科名称" prop="subjectName">
          <el-input v-model="form.subjectName" placeholder="请输入学科名称" />
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="form.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitAdd">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects.js'
export default {
  props: {
    // 父传子,showDialog控制弹层显示隐藏
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      form: {
        subjectName: '',
        isFrontDisplay: 1
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  computed: {
    showTitle () {
      // 根据form id区分 编辑还是新增
      return this.form.id ? '修改学科' : '新增学科'
    }
  },
  methods: {
    closeDialog () {
      // 重置表单数据
      this.form = {
        subjectName: '',
        isFrontDisplay: 1
      }
      this.$refs.roleForm.resetFields()
      this.$emit('update:showDialog', false)
    },
    submitAdd () {
      this.$refs.roleForm.validate(async flag => {
        if (!flag) return
        if (this.form.id) {
          await update(this.form)
          this.$message.success('修改成功')
        } else {
          await add(this.form) // 调用新增接口
          this.$message.success('添加成功')
        }
        this.closeDialog()
        // 通知到父组件更新数据
        // this.$parent.getEmployeeList()
        // $parent慎用,因为如果把对应的组件,放在插槽里面就会有点问题
        this.$emit('subjects-add')
      })
    }
  }
}
</script>

<style scoped lang='less'></style>
